angular.module('GiveStock')

.controller('GiveStock.HouseCtrl', ['$scope', '$state', '$filter','GiveStockHomeService', 'User', 'Device', 'imanDialog', '$ionicLoading','$stateParams', function($scope, $state, $filter, GiveStockHomeService, User, Device, imanDialog, $ionicLoading,$stateParams) {
    
    var wareHouse = {};//仓库
    var houseNum = 0;//仓库数，焦点数
    $scope.houseData = { 
        houses:[],//存储仓库数据
        selectHouse:'',//选中的house
        activeIndex:0
    };
    

    function onkeydown(event) {
        var keyCode = event.keyCode;
        
        if (keyCode === 37) { //左
            
        } else if (keyCode === 38) { //上
            if ($scope.houseData.activeIndex > 0) {
                $scope.houseData.activeIndex--;  
            }
            else{
                $scope.houseData.activeIndex = 0;
            }
            $scope.$apply();
        } else if (keyCode === 39) { //右
            
        } else if (keyCode === 40) { //下
            if ($scope.houseData.activeIndex < houseNum) {
                $scope.houseData.activeIndex++;  
            }
            
            $scope.$apply();
        } else if (keyCode === 13) { // 确认
            $scope.initData($scope.houseData.houses[$scope.houseData.activeIndex]);
        }
    }
    

    $scope.initData = function(house) {
        wareHouse = house;
        $scope.houseData.selectHouse = wareHouse.Name;    
        window.localStorage.setItem("wareHouse", angular.toJson(wareHouse));
        $state.go('GiveStock');
    };
    
    function gethouses() {
        imanDialog.showLoading();
        GiveStockHomeService.getAllWareHouse().then(function(data){
            imanDialog.hideLoading();
            if(data){
                $scope.houseData.houses = data;
                for (var i = 0; i < data.length; i++) {
                    $scope.houseData.houses[i].index = i;
                }
                houseNum = $scope.houseData.houses.length;
                if(wareHouse){
                   $scope.houseData.selectHouse = wareHouse.Name;    
                }   
            }      
        },function(error){
            imanDialog.toastBottom("获取仓库数据失败");
            imanDialog.hideLoading();
        });
    }


    

    $scope.$on('$ionicView.afterEnter', function () {
        if(Device.isTV()){
            angular.element(document).keydown(onkeydown);
        }  
        wareHouse = angular.fromJson(window.localStorage.getItem("wareHouse"));
        if($scope.houseData.houses.length===0){
            gethouses();
        }
    });

    $scope.$on('$ionicView.beforeLeave', function () {
        if(Device.isTV()){
            
            angular.element(document).off('keydown', onkeydown);
        }      
    });

    
}]);